<?php 
namespace App\Http\Controllers\TongGaoApi;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Mysql\tonggao\article;
use App\Models\Mysql\tonggao\term;
use App\Models\Mysql\tonggao\term_detail;
use App\Models\Mysql\tonggao\sentence;

class SentenceController extends Controller
{
//	use GlobalData;

	const ROUTE_PREFIX = '/api/*';

	protected $request;

	protected $curTime;

	protected $debug;


	/**
	 * 创建新的`DictController`控制器实例
	 * @param \Illuminate\Http\Request $request
	 */
	public function __construct(Request $request)
	{
		$this->request = $request;
		$this->error = [];
		$this->curTime = time();

		if(config('app.debug')) {
			$this->debug = true;
			error_reporting(E_ALL | E_STRICT);
		} else {
			$this->debug = false;
		}
	}

	/**
	 * 7. 获取term_detail在句对中的相关信息
	 * @param article_id  稿件id
	 * @param seq_no_begin 句子在稿件中的开始序号，
	 * @param seq_no_end   句子在稿件中的结束序号，
	 * @param term_id       术语id
	 */

	public function get_sentence()
	{
        #接受参数
		
		$p = [
		       'term_id' => $this->request->term_id,
               'seq_no_end' => $this->request->seq_no_end,
               'seq_no_begin' => $this->request->seq_no_begin,
               'article_id' => $this->request->article_id
             ];
        #Added by lishu to check the type of input parameters
		$p['article_id'] = intval($p['article_id']);
		if ( !is_numeric($p['seq_no_end']) ||! is_numeric($p['seq_no_begin']) || empty($p['article_id'])){
			return responseJson('parameter', "参数类型错误", FALSE);
		}
		$p['seq_no_end'] = intval($p['seq_no_end']);
		$p['seq_no_begin'] = intval($p['seq_no_begin']);
		
		if (!empty($p['term_id'])){
			$p['term_id'] = intval($p['term_id']);
			if (empty($p['term_id'])){
				return responseJson('parameter', "参数term_id类型错误", FALSE);
			}
		}
		#End of Added by lishu
		
		#Added by lishu
		$sql = "select id,seq_no,content,translation from sentence where seq_no>=".$p['seq_no_begin']." and seq_no<=".$p['seq_no_end']." and article_id=".$p['article_id']." order by seq_no";
		//echo ($sql);
		$sentences=sentence::select($sql);
		//print_r($sentences);
		
		foreach($sentences as $sentence){
			if (!empty($p['term_id'])){
				$sql = "select occur_no, chinese_pos,english, english_pos from term_detail where sentence_id=".$sentence->id." and term_id=".$p['term_id'];
				$r2 = term_detail::select($sql);
				$sentence->terms=$r2;
				//var_dump($r2);
			}
		}
		return responseJson('ok', array_merge($sentences), TRUE);
		
		#End of Added by lishu
		
        #取出术语，句子，日志
        #$term=term::term_info($p); #commented out by lishu		
        #$s_id=[];
        #$term_info=[];
        #$sentence_info=[];
        #foreach ($term as $k => $v)
        #{
        #    $s_id[]=$v->sentence_id;
        #    $term_info['term']['term_id']=$v->id;
        #    $term_info['term']['chinese_key']=$v->chinese_key;
        #    $term_info['term']['chinese_explanation']=$v->chinese_explanation;
        #    $term_info['term']['english']=$v->english;
        #    
        #    $sentence_info['sentence'][$k]['tonggao_changed']=$v->tonggao_changed;
        #	$sentence_info['sentence'][$k]['english_pos']=$v->english_pos;
        #	$sentence_info['sentence'][$k]['chinese_pos']=$v->chinese_pos;
        #	$sentence_info['sentence'][$k]['occur_no']=$v->occur_no;
        #	$sentence_info['sentence'][$k]['term_detail_id']=$v->term_detail_id;
        #
        #    $term_info['term_log'][$k]['chinese_explanation']=$v->chinese_explanation;
        #    $term_info['term_log'][$k]['modifier']=$v->chinese_explanation;
        #    $term_info['term_log'][$k]['modify_time']=$v->chinese_explanation;
        #    $term_info['term_log'][$k]['comment']=$v->comment;
        #}
        #$sentence=sentence::sentence_info($s_id);
        #foreach ($sentence as $k => $v) 
        #{
        #	# code...
        #	$sentence_info['sentence'][$k]['sentence_id']=$v->id;
        #	$sentence_info['sentence'][$k]['seq_no']=$v->seq_no;
        #	$sentence_info['sentence'][$k]['content']=$v->content;
        #	$sentence_info['sentence'][$k]['translation']=$v->translation;
        #	
        #
        #	$sentence_info['sentence_log'][$k]['translation_log']=$v->translation_log;
        #	$sentence_info['sentence_log'][$k]['modifier']=$v->modifier;
        #	$sentence_info['sentence_log'][$k]['modify_time']=$v->modify_time;
        #	$sentence_info['sentence_log'][$k]['comment']=$v->comment;
        #
        #}
       // echo '<pre>';
       // var_dump($term_info);
       // var_dump($sentence_info);die;
		#return responseJson('ok', array_merge($term_info,$sentence_info), TRUE);
	}


    /**
	 * 6. 获取某个术语在龙泉寺审定数据库的信息
	 * @param chinese_key  中文术语
	 */

    #59.110.218.46:8081/getVocabulary  参数 search 直接返回请求参数 post请求
    public function get_term_info()
    {
        #接受参数
		$p = ['search' => $this->request->chinese_key];
		$url="http://59.110.218.46:8081/getVocabulary?";
		$data=$this->https($url,$p);
		$r=json_decode($data,true);
        if($r=='[]')
        {
            return responseJson('ok', [], TRUE);
        }
		$r1=[];
		$r1['chinese_explanation']=$r[0]['interpretation'][0]['statement'];
		$r1['english']=$r[0]['english'];
        return responseJson('ok', $r1, TRUE);

    }

    public  function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSLVERSION, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    public function  ce()
    {
        $url="http://tg.com/api/tonggao/update_term_detail";
        $p = [
            'term_detail_id' => 18,
            'new_sentence_translation' => 'zuixindeceshi2222',
            'new_term_english' => 'ceshide222212',
            'comment' => '基础测试2221'
        ];

       $data=$this->https_request($url,$p);
       echo '<pre>';
       print_r(json_decode($data,true));
    }

	/**
	 * 9&10. 获取term_detail在句对中的相关信息
	 * @param article_id  稿件id
	 * @param seq_no_begin_offset 句子在稿件中的开始序号的偏移量，详见文档
	 * @param seq_no_end_offset   句子在稿件中的结束序号的偏移量，详见文档
	 * @param term_id       术语id
	 */

	public function get_sentence_of_prev_term_detail()
	{
		return($this->get_sentence_of_prev_next_term_detail('prev'));
    } 
	
	public function get_sentence_of_next_term_detail()
	{
		return($this->get_sentence_of_prev_next_term_detail('next'));
    } 
	
	public function get_sentence_of_prev_next_term_detail($direction)
	{
		#接受参数
		$p = [
		       'term_id' => $this->request->term_id,
			   'seq_no'  => $this->request->seq_no,
			   'occur_no'  => $this->request->occur_no,
               'seq_no_end' => $this->request->seq_no_end,
               'seq_no_begin' => $this->request->seq_no_begin,
               'article_id' => $this->request->article_id
             ];
			 
        #Check the type of input parameters
		$p['seq_no'] = intval($p['seq_no']);
		$p['seq_no_end'] = intval($p['seq_no_end']);
		$p['seq_no_begin'] = intval($p['seq_no_begin']);
		$p['article_id'] = intval($p['article_id']);
		$p['term_id'] = intval($p['term_id']);
		if (empty($p['seq_no']) || !is_numeric($p['occur_no']) || empty($p['seq_no_end']) ||empty($p['seq_no_begin']) || empty($p['article_id']) || empty($p['term_id'])){
			return responseJson('parameter', "参数类型错误", FALSE);
		}
		$p['occur_no'] = intval($p['occur_no']);

		if($direction=='next'){
			$sql = "select sentence.seq_no from term_detail, sentence where sentence.article_id=".$p['article_id']." and term_detail.term_id=".$p['term_id']." and term_detail.sentence_id=sentence.id and (sentence.seq_no>".$p['seq_no']." or (sentence.seq_no=".$p['seq_no']." and occur_no>".$p['occur_no'].")) order by sentence.seq_no, term_detail.occur_no limit 1";			
		} else{
			$sql = "select sentence.seq_no from term_detail, sentence where sentence.article_id=".$p['article_id']." and term_detail.term_id=".$p['term_id']." and term_detail.sentence_id=sentence.id and (sentence.seq_no<".$p['seq_no']." or (sentence.seq_no=".$p['seq_no']." and occur_no<".$p['occur_no'].")) order by sentence.seq_no desc, term_detail.occur_no desc limit 1";			
		}
		
		//echo $sql;
		$r = term_detail::select($sql);
		
		if (empty($r)){
			return responseJson('ok',[], TRUE);
		}
		
		//echo "seq_no=".$r[0]->seq_no."<br/>";
		$this->request->seq_no_begin = $r[0]->seq_no - $p['seq_no_begin'];
		$this->request->seq_no_end = $r[0]->seq_no + $p['seq_no_begin'];
		//$r = $this->get_sentence();
		//var_dump($r);
		return($this->get_sentence());
	}
	
    /**
     * 8. 修改term_detail
     * @param  term_detail_id	Integer	是	句对id
     * @param  new_sentence_translation	Text	是	修改后的的英文术语
     * @param  new_term_english	Text	是	修改后的英文句子
     * @param  comment	Text	是	修改原因
     */

     public  function  update_term_detail()
     {
         $p = [
             'term_detail_id' => $this->request->term_detail_id,
             'new_sentence_translation' => $this->request->new_sentence_translation,
             'new_term_english' => $this->request->new_term_english,
             'comment' => $this->request->comment
         ];

		$p['new_term_english']=str_replace(chr(194).chr(160)," ",$p['new_term_english']);
		$p['new_sentence_translation']=str_replace(chr(194).chr(160)," ",$p['new_sentence_translation']);
		
		//file_put_contents("\lishu.txt",print_r($p,true)."\r\n",8);
		//file_put_contents("\lishu.txt",$p['new_term_english']."\r\n",8);
		//file_put_contents("\lishu.txt",$p['new_sentence_translation']."\r\n",8);
		$r = pos_in_sentence($p['new_term_english'], $p['new_sentence_translation']);
		//file_put_contents("\lishu.txt",print_r($r,true),8);
		if(!empty($r)){
			$start_len_arr = array();
			foreach($r as $v){
				$start_len_arr []= $v['start'].",".$v['len'];
			}
			$p['new_english_pos'] = implode(";",$start_len_arr);
		} else {
			$p['new_english_pos'] = "";
		}
		//file_put_contents("\lishu.txt",$p['new_english_pos']."\r\n",8);
		//file_put_contents("\lishu.txt","aaa"."\r\n",8);
		//file_put_contents("\lishu.txt",$p['new_english_pos']."\r\n",8);
		//file_put_contents("\lishu.txt","is term = cow?".(($p['new_term_english']=="cow")?"true":"false")."\r\n",8);
		//file_put_contents("\lishu.txt","is sentence = one too cow?".(($p['new_sentence_translation']=="one too cow")?"true":"false")."\r\n",8);
		//for($i=0;$i<strlen($p['new_sentence_translation']);$i++){
		//	file_put_contents("\lishu.txt",ord(substr($p['new_sentence_translation'],$i,1))."  ",8);
		//}
		//file_put_contents("\lishu.txt","\r\n",8);
		//for($i=0;$i<strlen("one too cow");$i++){
		//	file_put_contents("\lishu.txt",ord(substr("one too cow",$i,1))."  ",8);
		//}
		//file_put_contents("\lishu.txt","\r\n",8);
		
         $result=term::update_term($p);
         if($result)
         {
             return responseJson('ok',[], TRUE);
         }
         else
         {
             return responseJson('亲，更新失败，请重试',[], TRUE);
         }

     }

    public function https($url,$data)
    {
        $timeout = 5000;
        $http_header = array(

            'Content-Type:application/x-www-form-urlencoded;charset=utf-8'
        );
        $postdata = 'search='.urlencode($data['search']);
        $ch = curl_init();
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_POST, 1);
        curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
        curl_setopt ($ch, CURLOPT_HEADER, false );
        curl_setopt ($ch, CURLOPT_HTTPHEADER,$http_header);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER,false); //处理http证书问题
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

        $result = curl_exec($ch);
        if (false === $result) {
            $result =  curl_errno($ch);
        }
        curl_close($ch);
        return $result;
    }



}